package com.example.myapplication;
import android.Manifest;

import androidx.annotation.NonNull;
import androidx.appcompat.app.ActionBar;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import androidx.core.content.FileProvider;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import android.app.Activity;
import android.content.ContentResolver;
import android.content.ContentUris;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.media.MediaScannerConnection;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.os.FileUtils;
import android.provider.DocumentsContract;
import android.provider.MediaStore;
import android.util.Log;
import android.view.Gravity;
import android.view.MotionEvent;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.Toast;

import com.alibaba.fastjson.JSON;
import com.bumptech.glide.Glide;
import com.example.myapplication.pojo.IotDataObj;
import com.example.myapplication.pojo.Line;
import com.example.myapplication.pojo.LineAdapter;
import com.example.myapplication.pojo.MyLineAdapter;
import com.example.myapplication.pojo.Res;
import com.example.myapplication.util.FileHelper;
import com.example.myapplication.util.MyQMUIDialog;
import com.example.myapplication.util.SpacesItemDecoration;
import com.github.chrisbanes.photoview.PhotoView;
import com.qmuiteam.qmui.util.QMUIStatusBarHelper;
import com.qmuiteam.qmui.widget.QMUIRadiusImageView;
import com.qmuiteam.qmui.widget.QMUITopBar;
import com.qmuiteam.qmui.widget.dialog.QMUIBottomSheet;
import com.qmuiteam.qmui.widget.roundwidget.QMUIRoundButton;

import org.jetbrains.annotations.NotNull;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.Headers;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

public class Line_Detection_Activity extends AppCompatActivity {
    int count =0;
    public static final int TAKE_PHOTO = 1;
    public static final int CHOOSE_PHOTO = 2;
    private Uri imageUri;
    private File outputImage;
    private QMUITopBar mTopBar;
    private RecyclerView listView;
    private List<Line> lines;
    private MyLineAdapter lineAdapter;
    private QMUIRoundButton choosebt;
    private QMUIRoundButton makebt;
    private QMUIRoundButton refresh_bt;
//    private PhotoView myiv;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_line_detection);
        ActionBar actionBar = getSupportActionBar();
        if (actionBar != null) {
            actionBar.hide();
        }
        mTopBar=findViewById(R.id.l_dtopbar);
        QMUIStatusBarHelper.translucent(this);// 沉浸式状态栏

        initTopBar();//初始化状态栏

        choosebt=findViewById(R.id.report_button1);
        makebt=findViewById(R.id.report_button2);
//        myiv=findViewById(R.id.myiv);
        refresh_bt=findViewById(R.id.refresh_bt);

        refresh_bt.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                lines.add(new Line(null,"http://101.34.248.186:8080/mypath/iot/imgs/line_imgs/posun.jpg",0,"A1","正常"));
                lines.add(new Line(null,"http://101.34.248.186:8080/mypath/iot/imgs/line_imgs/zhengchang.jpg",1,"A2","破损"));
                lineAdapter.setLines(lines);
            }
        });

        choosebt.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {


                if (ContextCompat.checkSelfPermission(Line_Detection_Activity.this, Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
                    ActivityCompat.requestPermissions(Line_Detection_Activity.this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, 1);
                } else {
                    openAlbum();

                }
            }
        });

        makebt.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {


                if (ContextCompat.checkSelfPermission(Line_Detection_Activity.this, Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) {
                    // 如果没有相机权限，请求权限
                    ActivityCompat.requestPermissions(Line_Detection_Activity.this, new String[]{Manifest.permission.CAMERA}, TAKE_PHOTO);
                } else {
                    // 如果已经有相机权限，可以启动相机应用
                    makeimg();
                }
            }
        });


        listView=findViewById(R.id.myline_listview);
        int space = 40;
        listView.addItemDecoration(new SpacesItemDecoration(space));
        initData();


    }

    //打开相册



    private void initData(){
        lines=new ArrayList<>();
        lines.add(new Line(null,"http://101.34.248.186:8080/mypath/iot/imgs/line_imgs/posun.jpg",0,"A1","正常"));
//        lines.add(new Line(null,"http://101.34.248.186:8080/mypath/iot/imgs/line_imgs/zhengchang.jpg",1,"A1","破损"));
//        lines.add(new Line(null,"http://101.34.248.186:8080/mypath/iot/imgs/line_imgs/1.jpg",0,"A1","严重破损"));
//        lines.add(new Line(null,"http://101.34.248.186:8080/mypath/iot/imgs/line_imgs/2.jpg",0,"A2","严重破损"));
//        lines.add(new Line(null,"http://101.34.248.186:8080/mypath/iot/imgs/line_imgs/3.jpg",0,"A3","严重破损"));
//        lines.add(new Line(null,"http://101.34.248.186:8080/mypath/iot/imgs/line_imgs/4.jpg",0,"A4","严重破损"));
//        lineAdapter=new LineAdapter(Line_Detection_Activity.this,R.layout.line_item,lines);
        lineAdapter=new MyLineAdapter(Line_Detection_Activity.this,lines);
        listView.setLayoutManager(new LinearLayoutManager(this)); // 使用线性布局管理器，你可以根据需要选择其他布局管理器

        listView.setAdapter(lineAdapter);

    }

    private void initTopBar() {
        mTopBar.setBackgroundColor(ContextCompat.getColor(this, R.color.blue));
        mTopBar.setTitleGravity(Gravity.LEFT);
        mTopBar.addLeftBackImageButton().setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
//                overridePendingTransition(R.anim.slide_still, R.anim.slide_out_right);
            }
        });

        mTopBar.setTitle("线路检测");
    }


    //拍照
    private void makeimg(){
        outputImage = new File(getExternalFilesDir(Environment.DIRECTORY_PICTURES),"last.jpg");
        if (outputImage.exists())
            outputImage.delete();
        try {
            outputImage.createNewFile();
        } catch (IOException e) {
            e.printStackTrace();
        }
//注意com.example.yourpackage.provider要和provider声明中的一致
        imageUri = (Build.VERSION.SDK_INT>=Build.VERSION_CODES.N) ? FileProvider.getUriForFile(Line_Detection_Activity.this,"com.example.myapplication",outputImage) : Uri.fromFile(outputImage);
        Intent intent = new Intent("android.media.action.IMAGE_CAPTURE");
        intent.putExtra(MediaStore.EXTRA_OUTPUT, imageUri);
        startActivityForResult(intent,TAKE_PHOTO);
    }



    //选取图片
    private void openAlbum() {

        Intent intent = new Intent(Intent.ACTION_OPEN_DOCUMENT);
        intent.addCategory(Intent.CATEGORY_OPENABLE);
        intent.setType("image/*");
        startActivityForResult(intent,CHOOSE_PHOTO);

    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {



        switch (requestCode) {
            case TAKE_PHOTO:
                if (resultCode == Activity.RESULT_OK) {


                    displayImage(outputImage.getAbsolutePath());


                }
                break;
            case CHOOSE_PHOTO:
                if (resultCode == Line_Detection_Activity.RESULT_OK && data != null) {
                    if (data.getData() != null) {
                        imageUri = data.getData();
                        String fileAbsolutePath = FileHelper.getFileAbsolutePath(Line_Detection_Activity.this, imageUri);
                        Log.i("lxl", "aburi：" + fileAbsolutePath);
                        displayImage(fileAbsolutePath);

                    }
                }
            default:
                break;
        }
        super.onActivityResult(requestCode, resultCode, data);

    }


    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {

        switch (requestCode) {
            case 1:
                if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    openAlbum();
                } else {
                    Toast.makeText(this, "you denied the permission", Toast.LENGTH_SHORT).show();
                }
                break;

        }
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
    }







    //拿到图片路径之后处理图片
    private void displayImage(String imagePath) {
        if (imagePath != null) {

            Log.i("lxl", imagePath);

            //发请求
//            report(imagePath);

            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    Line line = new Line(null, imagePath, 0, "房间二", "破损");
                    lines.add(line);
                    lineAdapter.setLines(lines);
//                    Glide.with(Line_Detection_Activity.this)
//                            .load(imagePath)
//                            .into(myiv);
                }
            });

        } else {
            Toast.makeText(this, "failed to get image", Toast.LENGTH_SHORT).show();
        }
    }

     void report(String imagePath){
        Log.i("lxl","report " + imagePath);
        // 用于构建 Multipart 请求体
        MultipartBody.Builder multipartBuilder = new MultipartBody.Builder()
                .setType(MultipartBody.FORM);
        // 添加文件部分（图片）
        File imageFile = new File(imagePath);
         runOnUiThread(new Runnable() {
             @Override
             public void run() {
                 // 在这里使用 Glide 加载图片
//                 Glide.with(Line_Detection_Activity.this)
//                         .load(imageFile)
//                         .into(myiv);
             }
         });

         MediaType mediaType = MediaType.parse("multipart/form-data");
        RequestBody imageBody = RequestBody.create(mediaType, imageFile);
        multipartBuilder.addFormDataPart("image", imageFile.getName()+(count++), imageBody);
        RequestBody requestBody = multipartBuilder.build();

        OkHttpClient client = new OkHttpClient().newBuilder()
                .build();
        Headers headers = new Headers.Builder()
                 .add("appId", "f1a202b782204cd2b3259824b45bb55e")
                 .add("appSecret", "4257946fa360f31e94393ba795d11aa673a92")
                 .build();
        Request request = new Request.Builder()
//                .url("http://101.34.248.186:8084/reportLineDetection")
                .url("http://47.107.52.7:88/member/photo/image/upload")
                .headers(headers)
                .method("POST", requestBody)
                .build();
        Call call = client.newCall(request);

        call.enqueue(new Callback() {
            @Override
            public void onFailure(@NotNull Call call, @NotNull IOException e) {
                Log.i("lxl",e.getMessage());
                Log.e("lxl","error");

            }

            @Override
            public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException {

                String res = response.body().string();
                Log.i("lxl",res);
//                runOnUiThread(new Runnable() {
//                    @Override
//                    public void run() {
//
//                        //渲染ui
//
//                    }
//                });

            }
        });
    }

}